package com.jpcc.vw.onlineRadio.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.support.v7.widget.LinearLayoutManager;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
/*Start by menglingqiang*/
import android.util.Log;
/*End by menglingqiang*/

import com.cns.android.atmospherelamp.AtmosphereLampManager;
import com.cns.android.location.POIManager;
import com.jpcc.vw.onlineRadio.R;
import com.jpcc.vw.onlineRadio.adapter.LocalOnlineRadioInfoAdapter;
import com.jpcc.vw.onlineRadio.adapter.SimpleOnlineRadioInfoAdapter;
/*Start by menglingqiang*/
import com.jpcc.vw.onlineRadio.application.MusicApplication;
/*End by menglingqiang*/
import com.jpcc.vw.onlineRadio.constants.Constants;
import com.jpcc.vw.onlineRadio.model.IRadio;
import com.jpcc.vw.onlineRadio.model.action.OnlineRadioItemSelectedAction;
import com.jpcc.vw.onlineRadio.model.action.RefreshRadioPlayingAction;
import com.jpcc.vw.onlineRadio.model.action.WaveAction;
import com.jpcc.vw.onlineRadio.model.bean.Announcer;
import com.jpcc.vw.onlineRadio.model.bean.BaseBean;
import com.jpcc.vw.onlineRadio.model.bean.LiveRadioDetailBean;
import com.jpcc.vw.onlineRadio.model.bean.LocalOnlineRadioBean;
import com.jpcc.vw.onlineRadio.model.bean.LocalOnlineRadioEntity;
import com.jpcc.vw.onlineRadio.model.bean.OnlineRadioCityBean;
import com.jpcc.vw.onlineRadio.model.bean.OnlineRadioSimpleInfoBean;
import com.jpcc.vw.onlineRadio.model.bean.OnlineRadioSimpleInfoEntity;
import com.jpcc.vw.onlineRadio.model.bean.RadioDeailBean;
import com.jpcc.vw.onlineRadio.model.bean.RadioSumBean;
import com.jpcc.vw.onlineRadio.model.bean.SubordinatedAlbum;
import com.jpcc.vw.onlineRadio.model.bean.Track;
import com.jpcc.vw.onlineRadio.model.impl.RadioImpl;
import com.jpcc.vw.onlineRadio.service.AlbumRadioAudioPlayer;
import com.jpcc.vw.onlineRadio.utils.CommonSubscriber;
import com.jpcc.vw.onlineRadio.utils.PermissionReq;
import com.jpcc.vw.onlineRadio.utils.ProcessInfoUtils;
import com.jpcc.vw.onlineRadio.utils.ToastUtils;
import com.jpcc.vw.onlineRadio.widget.CustomRecyclerView;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
/*Start by menglingqiang*/
import com.jpcc.vw.tracelog.TracelogInterface;
/*End by menglingqiang*/

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.ThreadMode;
import rx.Observable;
import rx.Subscriber;
import rx.functions.Action0;
import rx.functions.Func1;
import rx.functions.Func2;

public class OnlineRadioActivity extends com.jpcc.vw.onlineRadio.base.BaseActivity {

    @BindView(R.id.recyclerview_online_radio)
    CustomRecyclerView recyclerview_online_radio;
    @BindView(R.id.layout_back)
    RelativeLayout layout_back;
    @BindView(R.id.layout_search)
    RelativeLayout layout_search;
    @BindView(R.id.swipe_refrsh_online_radio)
    SmartRefreshLayout swipe_refrsh_online_radio;
    @BindView(R.id.tv_title)
    TextView tv_title;
    @BindView(R.id.tv_show_empty)
    TextView tv_show_empty;
    @BindView(R.id.imv_top_bottom_line)
    ImageView imv_top_bottom_line;
    @BindView(R.id.progress_circular)
    ProgressBar progress_circular;
    @BindView(R.id.imv_new_search)
    ImageView imv_new_search;

    private boolean is_refresh = true;
    private int page_index = 1;
    private double latitude = -1;
    private double langtitude = -1;

    private LocationManager locationManager;
    private SimpleOnlineRadioInfoAdapter adapter;
    private LocalOnlineRadioInfoAdapter localRadioAdapter;
    private List<OnlineRadioSimpleInfoEntity> datas = new ArrayList<>();
    private List<LocalOnlineRadioEntity> localRaiods = new ArrayList<>();
    private IRadio radioModel;
    LocationListener currentLocationChangeListener;
    private POIManager.CurrentLocationChangeListener mLocationChangeListener;

    @Override
    public int getLayoutId() {
        return R.layout.activity_online_radio;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Toast.makeText(OnlineRadioActivity.this, R.string.string_71, Toast.LENGTH_SHORT).show();
        }
    };


    private Handler requestHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            BrowseLocalRadios();
        }
    };

    @Override
    public void setupView() {
        ButterKnife.bind(this);
        tv_title.setText(getResources().getString(R.string.string_10));
        radioModel = new RadioImpl();
        EventBus.getDefault().register(this);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        layout_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                OnlineRadioActivity.this.finish();
            }
        });
        imv_new_search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent_search = new Intent(OnlineRadioActivity.this, SearchActivity.class);
                startActivity(intent_search);
            }
        });
        if (Constants.isRelease) {
            mLocationChangeListener = new POIManager.CurrentLocationChangeListener() {
                @Override
                public void onCurrentLocationChange(Bundle bundle) {
                    double localLatitude = 0.0000001 * bundle.getDouble(POIManager.POIConstants.DOUB_LATITUDE, 0);
                    double localLongitude = 0.0000001 * bundle.getDouble(POIManager.POIConstants.DOUB_LONGITUDE, 0);
                    Logger.i("onCurrentLocationChange-->" + localLatitude);
                    Logger.i("onCurrentLocationChange-->" + localLongitude);
                    double testLati = 39.92331837981574;
                    double testLon = 116.39592822799749;
                    com.cns.android.location.Location localLocation = com.cns.android.location.Location.from(testLati, testLon);
                    if (localLocation != null) {
                        Logger.i("location number-->" + testLati + " ," + testLon);
                        Logger.i("location valid-->" + localLocation.isValid());
                    }


                    if ((localLatitude > 0 && localLongitude > 0)) {
                        Logger.i("onCurrentLocationChange 1-->");
                        if (localLatitude != latitude || localLongitude != langtitude) {
                            Logger.i("onCurrentLocationChange 2-->");
                            if(langtitude==-1&&langtitude==-1){
                                latitude = localLatitude;
                                langtitude = localLongitude;
                                is_refresh = true;
                                requestHandler.sendEmptyMessage(0x01);
                            }
                        }
                    } else {
                        if(langtitude==-1&&langtitude==-1){
                            handler.sendEmptyMessage(0x98);
                            latitude = 0;
                            langtitude = 0;
                            Logger.i("onCurrentLocationChange 3-->");
                            requestHandler.sendEmptyMessage(0x01);
                        }
                    }
                }
            };
            try {
                POIManager.getInstance(this).registerListenCurrentLocation(mLocationChangeListener);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
        adapter = new SimpleOnlineRadioInfoAdapter(this, datas);
        localRadioAdapter = new LocalOnlineRadioInfoAdapter(this, localRaiods);
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setItemPrefetchEnabled(false);
        recyclerview_online_radio.setLayoutManager(manager);
        recyclerview_online_radio.setAdapter(localRadioAdapter);
        swipe_refrsh_online_radio.setEnableRefresh(false);
        if (false) {
            currentLocationChangeListener = new LocationListener() {
                @Override
                public void onLocationChanged(Location location) {
                    Logger.i("onLocationChanged()--->");
//                    if (latitude == 0 || langtitude == 0) {
                    latitude = location.getLatitude();
                    langtitude = location.getLongitude();
                    Logger.i("latitude--->" + latitude);
                    Logger.i("langtitude--->" + langtitude);
                    is_refresh = true;
                    BrowseLocalRadios();
//                    }
                }

                @Override
                public void onStatusChanged(String s, int i, Bundle bundle) {
                    Logger.i("onStatusChanged()--->");
                }

                @Override
                public void onProviderEnabled(String s) {
                    Logger.i("onProviderEnabled()--->" + s);
                }

                @Override
                public void onProviderDisabled(String s) {
                    Logger.i("onProviderDisabled()--->" + s);
                }
            };
        }
        if (!Constants.isRelease) {
            BrowseLocalRadios();
        }
    }

    @Override
    public void setupData() {
        swipe_refrsh_online_radio.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                is_refresh = true;
                swipe_refrsh_online_radio.setEnableLoadmore(true);
                BrowseLocalRadios();
            }
        });
        swipe_refrsh_online_radio.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                is_refresh = false;
                BrowseLocalRadios();
            }
        });
//        doRequestLocation();
        if (Constants.isRelease) {
            try {
                boolean atmosphereStatus = AtmosphereLampManager.getInstance(this).isHmiAtmosphereLampOn();
                String color = AtmosphereLampManager.getInstance(this).getHmiAtmosphereLampColor();
                doAtmosphere(atmosphereStatus, color);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void doAtmosphere(boolean rgbOn, String color) {
        Logger.i("doAtmosphere" + "rgbOn-->" + rgbOn);
        Logger.i("doAtmosphere" + "color-->" + color);
        if (rgbOn) {
            if (TextUtils.isEmpty(color)) {
                imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
            } else {
                imv_top_bottom_line.setColorFilter(Color.parseColor(color));
            }
        } else {
            imv_top_bottom_line.setColorFilter(Color.TRANSPARENT);
        }
    }


    private void BrowseLocalRadios() {
        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), OnlineRadioActivity.this.getClass().getName(), "DEBUG", null, "BrowseLocalRadios request");
            } else {
                Log.e("jgj", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


        int local_page = page_index;
        if (is_refresh) {
            local_page = 1;
        }








        /*End by menglingqiang*/
        if(!Constants.isRelease){
            latitude=0;
            langtitude=0;
        }
        radioModel.BrowseLocalRadios(latitude + "", langtitude + "", local_page).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                if (is_refresh){
//                    showProgress();
                    progress_circular.setVisibility(View.VISIBLE);
                }
            }
        })
                .subscribe(new CommonSubscriber<LocalOnlineRadioBean>() {
                    @Override
                    public void onSuccess(LocalOnlineRadioBean response) {
                        progress_circular.setVisibility(View.INVISIBLE);
                        if(is_refresh) {
//                            hideProgress();
                        }
                        swipe_refrsh_online_radio.finishRefresh();
                        swipe_refrsh_online_radio.finishLoadmore();


                        if (response.getData() != null && response.getData().getItems() != null && response.getData().getItems().size() > 0) {
                            if (is_refresh) {
                                localRaiods.clear();
                                page_index = 1;
                            }
                            is_refresh = false;
                            page_index++;
//                    localRaiods.clear();
                            localRaiods.addAll(response.getData().getItems());
                            localRadioAdapter.setDatas(localRaiods);
                            tv_show_empty.setVisibility(View.GONE);
                        } else {
                            swipe_refrsh_online_radio.finishLoadmore();
                            swipe_refrsh_online_radio.setEnableLoadmore(false);
                            if (is_refresh) {
                                tv_show_empty.setVisibility(View.VISIBLE);
                            }
                        }



                        /*Start by menglingqiang*/
                        Date dt = new Date();
                        try {
                            TracelogInterface inter = MusicApplication.getLogInterface();
                            if (inter != null) {
                                inter.sendLogData(dt.toString(), dt.toString(), OnlineRadioActivity.this.getClass().getName(), "DEBUG", response.getStatusCode().toString(), "BrowseLocalRadios onSuccess");
                            } else {
                                Log.e("jgj", "inter == null");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        /*End by menglingqiang*/
                    }

                    @Override
                    public void onFailure(BaseBean response) {
                        progress_circular.setVisibility(View.INVISIBLE);
                        if(is_refresh){
//                            hideProgress();
                        }
                        if(is_refresh){
                            tv_show_empty.setVisibility(View.VISIBLE);
                        }
                        swipe_refrsh_online_radio.finishRefresh();
                        ToastUtils.show(response.getStatusMessage());
                        /*Start by menglingqiang*/
                        Date dt = new Date();
                        try {
                            TracelogInterface inter = MusicApplication.getLogInterface();
                            if (inter != null) {
                                inter.sendLogData(dt.toString(), dt.toString(), OnlineRadioActivity.this.getClass().getName(), "ERROR", response.getStatusCode().toString(), "BrowseLocalRadios onFailure");
                            } else {
                                Log.e("jgj", "inter == null");
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        /*End by menglingqiang*/
                    }
                });
    }

    private void doRequestLocation() {
//        if (latitude == 0 || langtitude == 0) {
        PermissionReq.with(this)
                .permissions(Manifest.permission.ACCESS_FINE_LOCATION,
                        Manifest.permission.ACCESS_COARSE_LOCATION).result(new PermissionReq.Result() {
            @SuppressLint("MissingPermission")
            @Override
            public void onGranted() {
                //1.获取位置管理器
                locationManager = (LocationManager) OnlineRadioActivity.this.getSystemService(Context.LOCATION_SERVICE);
                //2.获取位置提供器，GPS或是NetWork
                List<String> providers = locationManager.getProviders(true);
                String locationProvider = "";
                if (providers.contains(LocationManager.GPS_PROVIDER)) {
                    //如果是网络定位
                    locationProvider = LocationManager.GPS_PROVIDER;
                } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
                    //如果是GPS定位
                    locationProvider = LocationManager.NETWORK_PROVIDER;
                } else {
                    ToastUtils.show("没有可用的位置提供器");
                    return;
                }

                //3.获取上次的位置，一般第一次运行，此值为null
                Location location = locationManager.getLastKnownLocation(locationProvider);
                Logger.i("onGranted()--->" + location);
                if (location != null) {
                    is_refresh = true;
                    latitude = location.getLatitude();
                    langtitude = location.getLongitude();
                    BrowseLocalRadios();
                } else {
                    // 监视地理位置变化，第二个和第三个参数分别为更新的最短时间minTime和最短距离minDistace
//                locationManager.requestLocationUpdates(locationProvider, 2000, 1,currentLocationChangeListener);
                    is_refresh = true;
                    latitude = 0;
                    langtitude = 0;
                    BrowseLocalRadios();
                    locationManager.requestLocationUpdates(locationProvider, 2000, 0, currentLocationChangeListener);
                    ToastUtils.show(R.string.string_71);
                }
            }

            @Override
            public void onDenied() {
                ToastUtils.show(R.string.string_26);
                OnlineRadioActivity.this.finish();
            }
        }).request();
//        }
    }

    private void doRequestCityRadio() {
        int local_page = page_index;
        if (is_refresh) {
            local_page = 1;
        }
//        if (latitude != 0 && langtitude != 0) {
        int finalLocal_page = local_page;

        /*Start by menglingqiang*/
        Date dt = new Date();
        try {
            TracelogInterface inter = MusicApplication.getLogInterface();
            if (inter != null) {
                inter.sendLogData(dt.toString(), dt.toString(), OnlineRadioActivity.this.getClass().getName(), "DEBUG", null, "GetRadioCode request");
            } else {
                Log.e("jgj", "inter == null");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        /*End by menglingqiang*/

        radioModel.GetRadioCode(latitude + "", langtitude + "").flatMap(new Func1<OnlineRadioCityBean, Observable<OnlineRadioSimpleInfoBean>>() {
            @Override
            public Observable<OnlineRadioSimpleInfoBean> call(OnlineRadioCityBean onlineRadioCityBean) {
                if (Constants.STATUS_SUCCESS_CODE == onlineRadioCityBean.getCode()) {
                    return radioModel.GetRadiosByCity(onlineRadioCityBean.getData().get(0).getCode(), finalLocal_page);
                } else {
                    OnlineRadioSimpleInfoBean info = new OnlineRadioSimpleInfoBean();
                    info.setCode(onlineRadioCityBean.getCode());
                    info.setStatusMessage(onlineRadioCityBean.getStatusMessage());
                    return Observable.just(info);
                }
            }
        }).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new CommonSubscriber<OnlineRadioSimpleInfoBean>() {
            @Override
            public void onSuccess(OnlineRadioSimpleInfoBean response) {
                hideProgress();
                swipe_refrsh_online_radio.finishRefresh();
                swipe_refrsh_online_radio.finishLoadmore();

                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), OnlineRadioActivity.this.getClass().getName(), "DEBUG", response.getStatusCode().toString(), "GetRadioCode onSuccess");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/

                if ((response.getData().getRadios() != null) && (response.getData().getRadios().size() > 0)) {
                    if (is_refresh) {
                        datas.clear();
                        page_index = 1;
                    }
                    datas.addAll(response.getData().getRadios());
                    adapter.setDatas(datas);
                    adapter.notifyDataSetChanged();
                    page_index++;
                } else {
                    swipe_refrsh_online_radio.finishLoadmore();
                    swipe_refrsh_online_radio.setEnableLoadmore(false);
                }
            }

            @Override
            public void onFailure(BaseBean response) {
                hideProgress();
                ToastUtils.show(response.getStatusMessage());
                swipe_refrsh_online_radio.finishRefresh();

                /*Start by menglingqiang*/
                Date dt = new Date();
                try {
                    TracelogInterface inter = MusicApplication.getLogInterface();
                    if (inter != null) {
                        inter.sendLogData(dt.toString(), dt.toString(), OnlineRadioActivity.this.getClass().getName(), "ERROR", response.getStatusCode().toString(), "GetRadioCode onFailure");
                    } else {
                        Log.e("jgj", "inter == null");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                /*End by menglingqiang*/
            }
        });
//        }
    }

    public void onEvent(OnlineRadioItemSelectedAction action) {
        if (Constants.isRelease) {
            ConnectivityManager connectivityManager = (ConnectivityManager) OnlineRadioActivity.this.getSystemService(Context.CONNECTIVITY_SERVICE);
            boolean connected = connectivityManager.getNetworkStatus();
            Logger.i("OnlineRadio network status-->" + connected);
            if (!connected) {
                if (ProcessInfoUtils.isForeground(MusicApplication.GetInstance())) {
//                    ToastUtils.show(getResources().getString(R.string.string_87));
                }
            }
        }
        getLiveingProgramDetail(localRaiods.get(action.getPosition()).getId(), action.getPosition());
//        getLiveingProgramDetail(1789, action.getPosition());
    }


    public void onEvent(WaveAction action) {
        adapter.notifyDataSetChanged();
    }

    public void onEvent(RefreshRadioPlayingAction action) {
        adapter.notifyDataSetChanged();
    }

    private void getLiveingProgramDetail(long radioId, int position) {
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK);

        Observable.zip(radioModel.GetPlayingProgramDetail(radioId), radioModel.getLiveSchedules(radioId, weekday - 1), new Func2<LiveRadioDetailBean, RadioDeailBean, RadioSumBean>() {
            @Override
            public RadioSumBean call(LiveRadioDetailBean liveRadioDetailBean, RadioDeailBean radioDeailBean) {
                RadioSumBean response = new RadioSumBean();
                if (liveRadioDetailBean.getCode() == 0 && radioDeailBean.getCode() == 0) {
                    response.setLiveRadio(liveRadioDetailBean);
                    response.setRadioSchedule(radioDeailBean);
                    return response;
                }
                return response;
            }
        }).doOnSubscribe(new Action0() {
            @Override
            public void call() {
                showProgress();
            }
        }).subscribe(new Subscriber<RadioSumBean>() {
            @Override
            public void onCompleted() {
                hideProgress();
            }

            @Override
            public void onError(Throwable e) {
                hideProgress();
            }

            @Override
            public void onNext(RadioSumBean radioSumBean) {
                hideProgress();
                List<Track> sources = new ArrayList<>();


                if (radioSumBean.getRadioSchedule() != null && radioSumBean.getRadioSchedule().getData() != null) {
                    for (RadioDeailBean.RadioSchedule schedule : radioSumBean.getRadioSchedule().getData()) {
                        if (!TextUtils.isEmpty(schedule.getListenBackUrl())) {
                            Track track = new Track();
                            SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                            subordinatedAlbum.setId(radioId);
                            subordinatedAlbum.setAlbumTitle(localRaiods.get(position).getName());
                            Announcer announcer = new Announcer();
                            announcer.setNickname("");
                            track.setId(schedule.getId());
                            track.setTrackTitle(schedule.getRelatedProgram().getProgramName());
                            track.setCoverUrlLarge(schedule.getRelatedProgram().getBackPicUrl());
                            track.setPlayUrl32(schedule.getListenBackUrl());
                            track.setCanDownload(false);
                            track.setDownloadUrl("");
                            track.type = "radio";
                            track.setSubordinatedAlbum(subordinatedAlbum);
                            track.setAnnouncer(announcer);
                            track.setLive(false);


                            SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
                            long endInt = 0;
                            long startInt = 0;
                            try {
                                if (schedule.getEndTime().equals("00:00")) {
                                    schedule.setEndTime("24:00");
                                }
                                Date end = sdf.parse(schedule.getEndTime());
                                endInt = end.getTime();
                                Date start = sdf.parse(schedule.getStartTime());
                                startInt = start.getTime();
                                Logger.i("endtime-startTime--->" + (endInt - startInt) / 1000);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            track.setStartTime(schedule.getStartTime());
                            track.setEndString(schedule.getEndTime());
                            track.setDuration((endInt - startInt) / 1000);


                            sources.add(track);
                        }
                    }
                }


                Track liveRadio = new Track();
                if (radioSumBean.getLiveRadio() != null) {
                    LiveRadioDetailBean response = radioSumBean.getLiveRadio();
                    SubordinatedAlbum subordinatedAlbum = new SubordinatedAlbum();
                    subordinatedAlbum.setId(radioId);
                    subordinatedAlbum.setAlbumTitle(localRaiods.get(position).getName());
                    Announcer announcer = new Announcer();
                    announcer.setNickname("");
                    liveRadio.setId(response.getData().getId());
                    liveRadio.setTrackTitle(response.getData().getProgramName());
                    liveRadio.setCoverUrlLarge(response.getData().getBackPicUrl());
                    liveRadio.setPlayUrl32(response.getData().getRate24AacUrl());
                    liveRadio.setCanDownload(false);
                    liveRadio.setDownloadUrl("");
                    liveRadio.type = "radio";
                    liveRadio.setSubordinatedAlbum(subordinatedAlbum);
                    liveRadio.setAnnouncer(announcer);
                    liveRadio.setLive(true);
                }
                Constants.LastModeFlag = false;
//                AlbumRadioAudioPlayer.get().setOnSources(sources, 0, 4, -1);
                AlbumRadioAudioPlayer.get().setOnSourcesForRadio(sources, liveRadio, true, 0);
                localRadioAdapter.notifyDataSetChanged();

            }
        });
    }

    @Override
    protected void onDestroy() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        if (mLocationChangeListener != null) {
            try {
                POIManager.getInstance(OnlineRadioActivity.this).unregisterListenCurrentLocation(mLocationChangeListener);
                if (handler != null) {
                    handler.removeCallbacksAndMessages(null);
                }
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        if (requestHandler != null) {
            requestHandler.removeCallbacksAndMessages(null);
        }
        super.onDestroy();
    }
}
